package com.jeeplus.modules.common.excel.common.validator.impl.base;

import com.jeeplus.common.utils.StringUtil;
import com.jeeplus.modules.common.excel.common.anno.base.IsNumberData;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;
import com.jeeplus.modules.common.utils.CommonUtils;

import java.lang.reflect.Field;

/**
 * 数字校验
 * @author wang.yishu
 */
public class IsNumberValidator extends AbstractValidator {

    private IsNumberData isNumberData;

    @Override
    public boolean canValidate(Field field) {
        isNumberData = field.getDeclaredAnnotation(IsNumberData.class);
        return isNumberData != null;
    }

    @Override
    public String toValidate(Object entity, Field field) {
        if (entity == null) return isNumberData.msg();
        field.setAccessible(true);
        try {
            Object value = field.get(entity);
            if (value == null) return null;
            int integerPlace = isNumberData.integerPlace();
            int decimalPlace = isNumberData.decimalPlace();
            if (value instanceof String) {
                String valueStr = value.toString();
                String[] split = valueStr.split("\\.");
                int length = 0;
                if ((length = split.length) > 2 || length < 1) {
                    return isNumberData.msg();
                }
                String integerStr = split[0];
                String decimalStr = length == 2 ? split[1] : null;
                boolean integerNumber = CommonUtils.isNumber(integerStr);
                if (!integerNumber) return isNumberData.msg();
                int integerLength = integerStr.length();
                if (integerLength > integerPlace) {
                    return isNumberData.msg();
                }
                if (StringUtil.isNotBlank(decimalStr)) {
                    boolean decimalNumber = CommonUtils.isNumber(decimalStr);
                    if (!decimalNumber) return isNumberData.msg();
                    int decimalLength = decimalStr.length();
                    if (decimalLength > decimalPlace) {
                        return isNumberData.msg();
                    }
                }
            } else if (value instanceof Integer || value instanceof Long || value instanceof Short) {
                if (decimalPlace != 0) {
                    return isNumberData.msg();
                } else {
                    return null;
                }
            } else if (value instanceof Double || value instanceof Float) {
                if (decimalPlace == 0) {
                    return isNumberData.msg();
                } else {
                    return null;
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
